package com.jianyun.jyzs.model;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jianyun.jyzs.bean.ContactBean;
import com.jianyun.jyzs.bean.User;
import com.jianyun.jyzs.http.Api;
import com.jianyun.jyzs.http.RetrofitHelper;
import com.jianyun.jyzs.model.imdoel.IContactModel;
import com.jianyun.jyzs.utils.EmptyHandle;
import com.jianyun.jyzs.utils.SysConstant2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangshijun on 2018/10/9.
 */

public class ContactModel implements IContactModel {

    private static ContactModel model;
    private final List<User> userArrayList;

    private ContactModel() {
        userArrayList = new ArrayList<>();
    }

    public static ContactModel getInstance() {
        if (model == null) {
            model = new ContactModel();
        }
        return model;
    }

    static int flag = 0;
    static int tag = 0;
    boolean isMore=false;
    @Override
    public void getContact(final String enterpriseCode, final String userId, String pageIndex, final OnLoadContactLisener onLoadContactLisener) {
        flag = 0;
        isMore=false;
        userArrayList.clear();
        final Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        api.loadContact("getAddressList", enterpriseCode, userId, pageIndex, "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        onLoadContactLisener.onFailed("获取通讯录失败！");
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            JSONObject object = new JSONObject(s);
                            if (object.getBoolean("result")) {//正常返回
                                int pageIndex1 = object.getInt("pageIndex");
                                int pageCnt = object.getInt("pageCnt");
                                Log.i("test","总数："+pageCnt);
                                if (pageCnt > 5) {
                                    for (int i = 1; i < 5 + 1; i++) {
                                        getMoreContact(api, 5, i, enterpriseCode, userId, onLoadContactLisener);
                                    }
                                } else {
                                    for (int i = 1; i < pageCnt + 1; i++) {
                                        getContactList(api, pageCnt, i, enterpriseCode, userId, onLoadContactLisener);
                                    }
                                }


                            } else {
                                String message = object.getString("message");
                                onLoadContactLisener.onFailed(message);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    }
                });
    }

    @Override
    public void onLoadMoreContact(String enterpriseCode, String userId, int pageIndex, int total, OnLoadContactLisener onLoadContactLisener) {
        final Api api = RetrofitHelper.builderErpHttp().create(Api.class);
        tag = pageIndex;
        for (int i = pageIndex+1; i < total + 1; i++) {
            getMoreContact(api, total, i, enterpriseCode, userId, onLoadContactLisener);
        }
        isMore=true;
    }


    public void getMoreContact(Api api, final int pageTotal, int pageIndex, final String enterpriseCode, final String userId, final OnLoadContactLisener onLoadContactLisener) {
        api.loadContact("getAddressList", enterpriseCode, userId, pageIndex + "", "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            tag = tag + 1;
                            JSONObject object = new JSONObject(s);
                            if (object.getBoolean("result")) {//正常返回
                                int pageIndex1 = object.getInt("pageIndex");
                                int pageCnt1 = object.getInt("pageCnt");
                                ContactBean contactBean = new Gson().fromJson(s, ContactBean.class);
                                List<ContactBean.ContactUser> list = contactBean.getList();
                                if (list!=null){
                                    if (list.size()==0||list.size()<50){
                                        Log.i("ysj","不在加载");
                                        onLoadContactLisener.onNoLoadMore(false);
                                    }else {

                                    }
                                }else {
                                    Log.i("ysj","不在加载");
                                    onLoadContactLisener.onNoLoadMore(false);
                                }
                                List<User> users = object2Users(s, userId, enterpriseCode,pageIndex1);
                                userArrayList.addAll(users);
                                if (tag == pageTotal) {
                                    Log.i("ysj","设置："+pageCnt1+"\n"+"pageIndex1:"+pageIndex1);
                                    Log.i("ysj","设置2："+pageTotal+"\n"+"tag:"+tag);
                                    onLoadContactLisener.setToal(pageCnt1,tag);
                                    onLoadContactLisener.onSuccess(userArrayList);
                                    if (!isMore){
                                        tag=0;
                                    }
                                }

                            } else {
                                String message = object.getString("message");
                                onLoadContactLisener.onFailed(message);
                            }

                            Log.i("ysj","不在加载："+tag);
                        } catch (Exception e) {
                            e.printStackTrace();

                        }


                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        onLoadContactLisener.onFailed("获取通讯录失败！");
                    }

                    @Override
                    public void onCompleted() {

                    }
                });
    }


    public void getContactList(Api api, final int pageCnt, int pageIndex1, final String enterpriseCode, final String userId, final OnLoadContactLisener onLoadContactLisener) {
        api.loadContact("getAddressList", enterpriseCode, userId, pageIndex1 + "", "jyzs", "Android", "1.0.2")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new Subscriber<Object>() {
                    @Override
                    public void onNext(Object o) {
                        String s = new Gson().toJson(o);
                        try {
                            flag += 1;
                            JSONObject object = new JSONObject(s);
                            if (object.getBoolean("result")) {//正常返回
                                int pageIndex1 = object.getInt("pageIndex");
                                int pageCnt1 = object.getInt("pageCnt");
                                ContactBean contactBean = new Gson().fromJson(s, ContactBean.class);
                                List<ContactBean.ContactUser> list = contactBean.getList();
                                List<User> users = object2Users(s, userId, enterpriseCode, pageIndex1);
                                if (users!=null){
                                    userArrayList.addAll(users);
                                }
                                if (flag == pageCnt) {
                                    onLoadContactLisener.setToal(pageCnt1,tag);
                                    onLoadContactLisener.onSuccess(userArrayList);
                                }
                                if (list!=null){
                                    if (list.size()==0||list.size()<50){
                                        Log.i("ysj","不在加载");
                                        onLoadContactLisener.onNoLoadMore(false);
                                    }else {

                                    }
                                }else {
                                    Log.i("ysj","不在加载");
                                    onLoadContactLisener.onNoLoadMore(false);
                                }
                            } else {
                                String message = object.getString("message");
                                onLoadContactLisener.onFailed(message);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        onLoadContactLisener.onFailed("获取通讯录失败！");
                    }

                    @Override
                    public void onCompleted() {

                    }
                });
    }

    /*
     * object转通讯录
     * object
     * userId 当前登录用户的serverUserId
     */
    public static List<User> object2Users(String json, String userId, String enterpriseCode,int pageIndex1) throws Exception {
        Log.i("test", "第几页：" + pageIndex1);
        List<User> users = new ArrayList<User>();
        User user = null;
        JSONObject obj = null;
        ContactBean contactBean = new Gson().fromJson(json, ContactBean.class);
        List<ContactBean.ContactUser> list = contactBean.getList();
        if (list!=null&&list.size()>0){
            for (int i = 0; i < list.size(); i++) {//遍历JSONArray

                user = new User();
                user.setId(null);
                user.setServerUserId(list.get(i).getId() + ""); // 用户ID
                user.setName(list.get(i).getUserName() + ""); // 账号
                user.setNameZh(list.get(i).getName() + ""); // 用户名称
                user.setEmail(list.get(i).getEmail() + ""); // 邮箱
                user.setPhoneNum(list.get(i).getPhoneNum() + "");//手机号
                user.setCompany(list.get(i).getCompany() + "");//所在单位
                user.setDepartment(list.get(i).getDepartment() + "");//所在部门
                user.setSex(list.get(i).getSex() + "");//性别
                user.setServerIconPath(list.get(i).getIconPaths() + ""); // 头像URL
                user.setUserType(SysConstant2.YES); // 用户类型,0:登录用户;1:朋友
                user.setUserId(userId);
                user.setEnterpriseCode(enterpriseCode);
                user.setOrderRank(list.get(i).getOrderRank() + "");//序列号
                user.setUnitId(list.get(i).getUnitId() + "");
                try {
                    user.setIsCommonContact(EmptyHandle.handleInt(list.get(i).getIsContact()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                users.add(user);
            }
            return users;
        }else {
            users.clear();
            return users;
        }

    }
}
